<?php

namespace Ignus\View\TokenParser;

use Ignus\View\TokenParser;
use Ignus\View\Node\Expression\AssignName;
use Ignus\View\Token;

class From extends TokenParser
{
    public function parse(Token $token)
    {
        $macro = $this->parser->getExpressionParser()->parseExpression();
        $stream = $this->parser->getStream();
        $stream->expect('import');

        $targets = array();
        do {
            $name = $stream->expect(Token::NAME_TYPE)->getValue();

            $alias = $name;
            if ($stream->test('as')) {
                $stream->next();

                $alias = $stream->expect(Token::NAME_TYPE)->getValue();
            }

            $targets[$name] = $alias;

            if (!$stream->test(Token::PUNCTUATION_TYPE, ',')) {
                break;
            }

            $stream->next();
        }
        while (true);

        $stream->expect(Token::BLOCK_END_TYPE);

        $node = new \Ignus\View\Node\Import($macro, new AssignName($this->parser->getVarName(), $token->getLine()), $token->getLine(), $this->getTag());

        foreach($targets as $name => $alias) {
            $this->parser->addImportedFunction($alias, $name, $node->getNode('var'));
        }

        return $node;
    }

    public function getTag()
    {
        return 'from';
    }
}
